package com.example.lenovo.asia5b.ui;

import android.app.Activity;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.lenovo.asia5b.home.activity.ForgotPasswordActivity;
import com.example.lenovo.asia5b.my.myWallet.activity.MyWalletActivity;
import com.example.lenovo.asia5b.util.CommonUtil;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.FileUtil;
import com.example.lenovo.asia5b.util.MoneyUtil;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.google.android.gms.plus.PlusShare;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.wushi.lenovo.asia5b.R;

import java.text.SimpleDateFormat;
import java.util.Date;

import fay.frame.ui.U;



public class LoadingDalog implements MoneyUtil.MoneyInterface{
	public  Dialog loadingDialog,iconDialog,passwordDialog,shareDialog;
	private Context context;
	private Uri photoUri;
	private PasswordView pwdView;
	private PasswordDialogInterface passwordDialogInterface;
	private TextView txt_account,txt_hint_cz;
	private MoneyUtil moneyUtil = null;
	private ImageView image_null;


	public LoadingDalog(Context context) {
		this.context = context;
        if (context instanceof PasswordDialogInterface) {
            this.passwordDialogInterface = (PasswordDialogInterface)context;
        }
	}

	public LoadingDalog(Context context,PasswordDialogInterface passwordDialogInterface) {
		this.context = context;
		this.passwordDialogInterface = passwordDialogInterface;
	}

	/**
	 * 显示加载中dialog
	 */
	public void show() {
		if (null ==loadingDialog) {
			LayoutInflater inflater = LayoutInflater.from(context);
			View v = inflater.inflate(R.layout.frame_view_progress, null);// 得到加载view
			LinearLayout layout = (LinearLayout) v
					.findViewById(R.id.dialog_loading_view);// 加载布局
			TextView tipTextView = (TextView) v.findViewById(R.id.tipTextView);// 提示文字
//		tipTextView.setText("加载中");// 设置加载信息

			loadingDialog = new Dialog(context, R.style.MyDialogStyle);// 创建自定义样式dialog
			loadingDialog.setCancelable(true); // 是否可以按“返回键”消失
			loadingDialog.setCanceledOnTouchOutside(false); // 点击加载框以外的区域
			loadingDialog.setContentView(layout, new LinearLayout.LayoutParams(
					LinearLayout.LayoutParams.MATCH_PARENT,
					LinearLayout.LayoutParams.MATCH_PARENT));// 设置布局
			/**
			 *将显示Dialog的方法封装在这里面
			 */
			Window window = loadingDialog.getWindow();
			WindowManager.LayoutParams lp = window.getAttributes();
			lp.width = WindowManager.LayoutParams.MATCH_PARENT;
			lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
			window.setGravity(Gravity.CENTER);
			window.setAttributes(lp);
			window.setWindowAnimations(R.style.PopWindowAnimStyle);
		}
		loadingDialog.show();
	}

	// 显示选择照片对话框
	public void showPhoto() {
		if (iconDialog == null) {
			View view = LayoutInflater.from(context).inflate(
					R.layout.frame_map_photo_choose_dialog, null);
			iconDialog = new Dialog(context, R.style.transparentFrameWindowStyle);
			iconDialog.setContentView(view, new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
			Window window = iconDialog.getWindow();
			window.setWindowAnimations(R.style.main_menu_animstyle);
			WindowManager.LayoutParams wl = window.getAttributes();

			Button dialog_chose_icon_camera = (Button) view
					.findViewById(R.id.dialog_chose_icon_camera);
			Button dialog_chose_icon_photo = (Button) view
					.findViewById(R.id.dialog_chose_icon_photo);
			Button dialog_chose_icon_cancel = (Button) view
					.findViewById(R.id.dialog_chose_icon_cancel);
			/**
			 * 拍照
			 */
			dialog_chose_icon_camera.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					SimpleDateFormat timeStampFormat = new SimpleDateFormat(
							"yyyy_MM_dd_HH_mm_ss");
					String filename = timeStampFormat.format(new Date());
					ContentValues values = new ContentValues();
					values.put(MediaStore.Images.Media.TITLE, filename);
					photoUri = context.getContentResolver().insert(
							MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
					((Activity)context).startActivityForResult(intent, CommonUtil.CHOOSE_CAMERA_INT);
					iconDialog.dismiss();
				}
			});
			/**
			 * 相册
			 * */
			dialog_chose_icon_photo.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent = new Intent();
					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					((Activity)context).startActivityForResult(intent, CommonUtil.CHOOSE_IMAGE_INT);
					iconDialog.dismiss();
				}
			});
			/**
			 * 取消
			 */
			dialog_chose_icon_cancel.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					iconDialog.dismiss();
				}
			});
			wl.x = 0;
			wl.y = ((Activity)context).getWindowManager().getDefaultDisplay().getHeight();
			wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
			wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
			iconDialog.onWindowAttributesChanged(wl);
			iconDialog.setCanceledOnTouchOutside(true);
		}
		iconDialog.show();
	}

	public static void startPhotoZoom(Uri uri,Activity activity) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		// crop为true是设置在开启的intent中设置显示的view可以剪裁
		intent.putExtra("crop", "true");
		// aspectX aspectY 是宽高的比例
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// outputX,outputY 是剪裁图片的宽高
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		intent.putExtra("return-data", true);
		intent.putExtra("noFaceDetection", true);
		activity.startActivityForResult(intent, 103);
	}

	TextView txt_money = null;

	// 显示输入密码对话框
	public void showPassword(String money) {
		if (null == passwordDialog){
			passwordDialog = new Dialog(context);
			moneyUtil = new MoneyUtil(this);
			moneyUtil.moneyData();
			passwordDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			View view = LayoutInflater.from(context).inflate(R.layout.view_payment_popup, null);
			view.setBackgroundColor(Color.parseColor("#ffffff"));
			TextView txt_forgot_password = (TextView)view.findViewById(R.id.txt_forgot_password);
			txt_hint_cz = (TextView)view.findViewById(R.id.txt_hint_cz);
			txt_account = (TextView)view.findViewById(R.id.txt_account);
			txt_hint_cz .getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
			txt_hint_cz.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent = new Intent(context, MyWalletActivity.class);
					dismiss();
					passwordDialog = null;
					context.startActivity(intent);
				}
			});
			if (null == SharedPreferencesUtils.getUserBean()) {
				txt_account.setText("RM 0.0");
			} else {
				txt_account.setText("RM "+SharedPreferencesUtils.getUserBean().user_money);
			}
			ImageView txt_hint = (ImageView)view.findViewById(R.id.txt_hint);
			txt_money = (TextView)view.findViewById(R.id.txt_money);
			txt_money.setText("RM "+ money);
			//忘记密码
			txt_forgot_password.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Intent intent = new Intent(context,ForgotPasswordActivity.class);
					intent.putExtra("from","paypassword");
					context.startActivity(intent);
					dismiss();
				}
			});
			pwdView = (PasswordView)view. findViewById(R.id.pwd_view);
			//添加密码输入完成的响应
			pwdView.setOnFinishInput(new OnPasswordInputFinish() {
				@Override
				public void inputFinish() {
					//输入完成后我们简单显示一下输入的密码
					//也就是说——>实现你的交易逻辑什么的在这里写
//					Toast.makeText(context, pwdView.getStrPassword(), Toast.LENGTH_SHORT).show();
                    passwordDialogInterface.gainPasswor(pwdView.getStrPassword());
					pwdView.hiddenKeyboard();
				}
			});
			//确定
			passwordDialog.setContentView(view);
			passwordDialog.setCanceledOnTouchOutside(true);
			Window dialogWindow = passwordDialog.getWindow();
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			//dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
			lp.width = WindowManager.LayoutParams.MATCH_PARENT;
			lp.height = DensityUtil.dip2px(context, 435);
			lp.gravity = Gravity.BOTTOM;
			dialogWindow.setAttributes(lp);
			dialogWindow.setBackgroundDrawableResource(R.color.transparent_all);
			passwordDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				@Override
				public void onCancel(DialogInterface dialogInterface) {
					pwdView.hiddenKeyboard2();
				}
			});
			txt_hint.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					U.Toast(context,context.getResources().getString(R.string.zfmm_hint));
				}
			});
		}
		if (null != txt_money) {
			txt_money.setText("RM "+ money);
		}
		passwordDialog.show();
	}

	/**
	 * 分享窗口
	 *
	 */
	public void showShare(String url,String title,String describe,String imagUrl,int imageId) {
		if (null == shareDialog){
			shareDialog = new Dialog(context);
			shareDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			View view = LayoutInflater.from(context).inflate(R.layout.view_share_popup, null);
			view.setBackgroundColor(Color.parseColor("#ffffff"));
			ImageView login_from_wechat = (ImageView) view.findViewById(R.id.login_from_wechat);
			ImageView login_from_qq  = (ImageView) view.findViewById(R.id.login_from_qq);
			ImageView login_from_sina  = (ImageView)view.findViewById(R.id.login_from_sina);
			ImageView login_from_facebook  = (ImageView)view.findViewById(R.id.login_from_facebook);
			ImageView login_from_google = (ImageView)view.findViewById(R.id.login_from_google);
			ImageView login_from_instagram = (ImageView)view.findViewById(R.id.login_from_instagram);
			 image_null = (ImageView)view.findViewById(R.id.image_null);
			Button btn_immediately_on = (Button)view.findViewById(R.id.btn_immediately_on);
			login_from_facebook.setOnClickListener(new ShareOnClick(url,title,describe,imagUrl,imageId));
			login_from_wechat.setOnClickListener(new ShareOnClick(url,title,describe,imagUrl,imageId));
			login_from_qq.setOnClickListener(new ShareOnClick(url,title,describe,imagUrl,imageId));
			login_from_sina.setOnClickListener(new ShareOnClick(url,title,describe,imagUrl,imageId));
			login_from_google.setOnClickListener(new ShareOnClick(url,title,describe,imagUrl,imageId));
			login_from_instagram.setOnClickListener(new ShareOnClick(url,title,describe,imagUrl,imageId));
			if (imageId==0) {
				login_from_instagram.setVisibility(View.INVISIBLE);
			}
			//确定
			shareDialog.setContentView(view);
			shareDialog.setCanceledOnTouchOutside(true);
			Window dialogWindow = shareDialog.getWindow();
			WindowManager.LayoutParams lp = dialogWindow.getAttributes();
			//dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
			lp.width = WindowManager.LayoutParams.MATCH_PARENT;
			lp.height = DensityUtil.dip2px(context, 240);
			lp.gravity = Gravity.BOTTOM;
			dialogWindow.setAttributes(lp);
			dialogWindow.setBackgroundDrawableResource(R.color.transparent_all);
			btn_immediately_on.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					shareDialog.dismiss();
				}
			});
		}
		shareDialog.show();
	}

	public class ShareOnClick implements View.OnClickListener {
		private  String url,title,describe,imagUrl;
		private int  imageId;
		private    Intent shareIntent = null ;
		public ShareOnClick(String url,String title,String describe,String imagUrl,int imageId) {
			this.url = url;
			this.title = title;
			this.describe = describe;
			this.imagUrl = imagUrl;
			this.imageId = imageId;
		}
		@Override
		public void onClick(View view) {
			if (TextUtils.isEmpty(url)){
				url = "https://asia5b.com/";
			}
			UMWeb web = new UMWeb(url);
			UMImage thumb = null;
			if (imageId == 0 ){
				thumb =  new UMImage(context, imagUrl);
				thumb.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩，默认为大小压缩，适合普通很大的图
				web.setTitle(title);//标题
				web.setThumb(thumb);  //缩略图
				web.setDescription(describe);//描述
			} else {
				thumb = new UMImage(context, imageId);//资源文件
			}

            ShareAction ss;
			switch (view.getId()) {
				case R.id.login_from_wechat:
					ss = new ShareAction((Activity) context)
							.setPlatform(SHARE_MEDIA.WEIXIN)//传入平台
							.setCallback(shareListener);
					if (imageId!=0) {
						ss.withMedia(thumb);
					} else {
						ss.withMedia(web);
					}
					ss.share();
					break;
				case R.id.login_from_qq:
					ss = new ShareAction((Activity) context)
							.setPlatform(SHARE_MEDIA.QQ)//传入平台
							.setCallback(shareListener);
					if (imageId!=0) {
						ss.withMedia(thumb);
					} else {
						ss.withMedia(web);
					}
					ss.share();
					break;
				case R.id.login_from_sina:
                    ss = new ShareAction((Activity) context)
                            .setPlatform(SHARE_MEDIA.SINA)//传入平台
                            .setCallback(shareListener);
                    if (imageId!=0) {
                        ss.withMedia(thumb);
                    } else {
                        ss.withMedia(web);
                    }
                    ss.share();
					break;
				case R.id.login_from_facebook:
                    ss = new ShareAction((Activity) context)
                            .setPlatform(SHARE_MEDIA.FACEBOOK)//传入平台
                            .setCallback(shareListener);
                    if (imageId!=0) {
                        ss.withMedia(thumb);
                    } else {
                        ss.withMedia(web);
                    }
                    ss.share();
					break;
				case  R.id.login_from_instagram:
					ss = new ShareAction((Activity) context)
							.setPlatform(SHARE_MEDIA.INSTAGRAM)//传入平台
							.setCallback(shareListener);
					if (imageId!=0) {
						ss.withMedia(thumb);
					} else {
						thumb = new UMImage(context, imagUrl);//资源文件
						ss.withMedia(thumb);
					}
					show();
					ss.share();
					break;
				case R.id.login_from_google:
					show();
					try {
						if (imageId == 0) {
							DisplayImageOptions options = new DisplayImageOptions.Builder()
									.cacheInMemory(true)                                          // 设置下载的图片是否缓存在内存中
									.cacheOnDisk(true)                                            // 设置下载的图片是否缓存在SD卡中
									.bitmapConfig(Bitmap.Config.ARGB_8888)
									.build();
							ImageLoader.getInstance().displayImage(imagUrl, image_null, options, new SimpleImageLoadingListener() {
								//刚加载
								@Override
								public void onLoadingStarted(String imageUri, View view) {
								}

								//加载失败
								@Override
								public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
									loadingDialog.dismiss();

								}

								//加载完成
								@Override
								public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
									Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(context.getContentResolver(), loadedImage, null, null));
									shareIntent = new PlusShare.Builder(context)
											.setType("image/*")      //  不变
											.setText(title + "\n" + url)   // 自定义内容
//										.setContentUrl(Uri.parse(url))   // 自定义链接地址
											.addStream(uri)
											.getIntent();
									((Activity) context).startActivityForResult(shareIntent, 0);
									loadingDialog.dismiss();
								}
							});
						} else {
							Uri selectedImage = FileUtil.getImageStreamFromExternal(Setting.SHARE_IMAG_NAME);
							PlusShare.Builder share = new PlusShare.Builder(context);
							share.setText("asia5b");
							share.addStream(selectedImage);
							share.setType("image/*");
							shareIntent = share.getIntent();
							try {
							} catch (ActivityNotFoundException e) {
								Toast.makeText(context, "You haven't installed google+ on your device", Toast.LENGTH_SHORT).show();
							}
							((Activity) context).startActivityForResult(shareIntent, 0);
							loadingDialog.dismiss();
						}
					} catch (Exception e) {
						U.Toast(context, context.getResources().getString(R.string.cnfx));
						dismiss();
					}
					break;
			}
		}
	}

	public interface PasswordDialogInterface {
        public void gainPasswor(String strPasswor);
	}

    /**
     * 清除输入框里面的密码
     */
	public void clearPassword(){
        if (null != pwdView) {
            pwdView.clear();
        }
    }

	/**
	 * 关闭dialog
	 *
	 *
	 */
	public void dismiss() {
		if (null !=loadingDialog) {
			loadingDialog.dismiss();
		}
		if (null !=iconDialog) {
			iconDialog.dismiss();
		}
		if (null !=passwordDialog) {
			passwordDialog.dismiss();
			pwdView.hiddenKeyboard2();
			//隐藏起来同时把密码清空
			pwdView.clear();
		}
	}

	public Uri getPhotoUrihotoUri() {
		return photoUri;
	}

	@Override
	public void money(String user_money,String pay_points) {
		txt_account.setText("RM "+user_money);
		//当支出数额大于账户余额的情况下，显示出  余额不足提示
		if (txt_money.getText().toString().compareTo(txt_money.getText().toString())<0) {
			txt_hint_cz.setVisibility(View.VISIBLE);
		} else{
			txt_hint_cz.setVisibility(View.GONE);
		}
	}


	private UMShareListener shareListener = new UMShareListener() {
		/**
		 * @descrption 分享开始的回调
		 * @param platform 平台类型
		 */
		@Override
		public void onStart(SHARE_MEDIA platform) {

		}

		/**
		 * @descrption 分享成功的回调
		 * @param platform 平台类型
		 */
		@Override
		public void onResult(SHARE_MEDIA platform) {
//			Toast.makeText(context,"成功了",Toast.LENGTH_LONG).show();
			dismiss();
		}

		/**
		 * @descrption 分享失败的回调
		 * @param platform 平台类型
		 * @param t 错误原因
		 */
		@Override
		public void onError(SHARE_MEDIA platform, Throwable t) {
//			Toast.makeText(context,"失败"+t.getMessage(),Toast.LENGTH_LONG).show();
			dismiss();
		}

		/**
		 * @descrption 分享取消的回调
		 * @param platform 平台类型
		 */
		@Override
		public void onCancel(SHARE_MEDIA platform) {
//			Toast.makeText(context,"取消了",Toast.LENGTH_LONG).show();
			dismiss();
		}
	};
}
